package com.justnow.offer;


import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * @author justnow
 * Created on 2020-09-04
 * Description
 */
public class Demo01 {
    private static final int CAPACITY = 10;
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        Productor p1 = new Productor("P1", queue, CAPACITY);
        Consumer c1 = new Consumer("C1", queue, CAPACITY);
        p1.start();
        c1.start();
    }
}

class Productor extends Thread {
    private Queue<Integer> queue;
    String name;
    int maxSize;
    int i = 0;

    public Productor(String name, Queue<Integer> queue, int maxSize) {
        this.name = name;
        this.queue = queue;
        this.maxSize = maxSize;
    }

    public void run() {
        while (true) {
            synchronized (queue) {
                if (queue.size() == maxSize) {
                    try {
                        System.out.println("队列已经满了，生产者[" + name + "]线程等待消费者从队列中消费产品。" );
                        queue.wait(); //调用对象的wait方法之后，该线程释放这个资源，并且处于wait状态
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("[" + name + "]生产的产品 ：" + i);
                queue.offer(i++);
                queue.notifyAll();

                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

class Consumer extends Thread {
    private Queue<Integer> queue;
    String name;
    int maxSize;

    public Consumer(String name, Queue<Integer> queue, int maxSize) {
        this.name = name;
        this.queue =queue;
        this.maxSize = maxSize;
    }

    public void run() {
        while (true) {
            synchronized (queue) {
                if (queue.isEmpty()) {
                    try {
                        System.out.println("队列是空的 消费者[" + name +"] 等待生产者生成");
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                int x = queue.poll();
                System.out.println("[" + name + "]消费的产品 : " + x);
                queue.notifyAll();
                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


}
